import Application from 'koa';
import Koa from 'koa';
import KoaJSON from 'koa-json';
import KoaBody from 'koa-body';
import GlobalAutoConfigurable from "@framework/config/GlobalAutoConfigurable";

/**
 * 封装服务类
 */
class KoaBootService {

    /**
     * 服务
     */
    private server: Application;

    /**
     * 构造函数
     */
    constructor() {
        this.server = new Koa();
        this.server.use(KoaJSON());
        this.server.use(KoaBody({
            multipart: true
        }));
    }

    /**
     * 服务启动类
     * @param port 端口号
     */
    public run(port?: number): Promise<string> {
        port = port? port : GlobalAutoConfigurable.server.port;
        return new Promise<string>((resolve, reject) => {
            this.server.listen(port, () => {
                resolve(`${port}`);
            });
            this.server.on("error", error => {
                reject();
            })
        })
    }

    /**
     * 注册中间件
     * @param object 中间件
     */
    public use(object: any): void {
        this.server.use(object);
    }
}

export default KoaBootService;